package com.csinc.generate.core.make.impl;

import com.csinc.generate.core.make.IMake;
import com.csinc.generate.core.base.model.GenBeanEntity;
import com.csinc.generate.core.base.model.GenerationEntity;
import com.csinc.generate.core.base.model.TemplateModel;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.StringWriter;
import java.io.Writer;
import java.util.*;

/**
 * FREEMARK 解析
 * Create By 郭金宝 on 2018/7/23.<br>
 */
@Slf4j
public class FreeMarkerMakeImpl implements IMake {
    private static final StringTemplateLoader resourceLoader = new StringTemplateLoader();

    private static Configuration cfg;

    static {
        try {
            cfg = new Configuration();
            cfg.setTemplateLoader(resourceLoader);
            cfg.setLocale(Locale.CHINA);
            cfg.setDefaultEncoding("UTF-8");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public List<String> makeByTemplateModel(GenerationEntity generationEntity, GenBeanEntity tableEntity, List<TemplateModel> fileList) {
        List<String> renderList = new ArrayList<String>();
        Template t;
        try {
            for (TemplateModel file : fileList) {
                resourceLoader.putTemplate(file.hashCode() + "_FTL+KEY", file.getFileModel().getFile());
                t = cfg.getTemplate(file.hashCode() + "_FTL+KEY");
                Writer write = new StringWriter();
                Map<String, Object> paramsMap = new HashMap<String, Object>();
                paramsMap.put(IMake.GEN_PARAMS, generationEntity);
                paramsMap.put(IMake.TABLE_DETAIL, tableEntity);
                t.process(paramsMap, write);
                log.info(write.toString());
                renderList.add(write.toString());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return renderList;
    }

    public List<String> make(GenerationEntity generationEntity, GenBeanEntity tableEntity, List<String> fileList) {
        List<String> renderList = new ArrayList<String>();
        Template t;
        try {
            for (String file : fileList) {
                resourceLoader.putTemplate(file.hashCode() + "_FTL+KEY", file);
                t = cfg.getTemplate(file.hashCode() + "_FTL+KEY");
                Writer write = new StringWriter();
                Map<String, Object> paramsMap = new HashMap<String, Object>();
                paramsMap.put(IMake.GEN_PARAMS, generationEntity);
                paramsMap.put(IMake.TABLE_DETAIL, tableEntity);
                t.process(paramsMap, write);
                log.info(write.toString());
                renderList.add(write.toString());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return renderList;
    }
}
